<template>
  <div class="number-container">
    <div class="less" :class="{ disabled: number <= min }" @click="descNumberHandler">-</div>
    <input v-model="number" @change="inputNumberHandler" />
    <div class="more" :class="{ disabled: number >= max }" @click="riseNumberHandler">+</div>
  </div>
</template>

<script>
export default {
  props: {
    min: {
      type: Number,
      default: 1
    },
    max: {
      type: Number,
      default: 10000000
    },
    value: {
      type: Number,
      default: 1
    }
  },

  created () {
    this.number = this.value
  },

  data () {
    return {
      number: 1
    }
  },

  methods: {
    /**
     * 减小数量
     */
    descNumberHandler () {
      // 如果当前是最小数量，则不操作
      if (this.min >= this.number) {
        this.number = this.min
        return
      }
      this.number--
      // 通知父组件值改变
      this.$emit('onChange', this.number)
    },

    /**
     * 增加数量
     */
    riseNumberHandler () {
      // 如果当前是最小数量，则不操作
      if (this.max <= this.number) {
        this.number = this.max
        return
      }
      this.number++
      // 通知父组件值改变
      this.$emit('onChange', this.number)
    },

    /**
     * 输入数量
     */
    inputNumberHandler () {
      // 如果当前是最小数量，则不操作
      if (this.min >= this.number) {
        this.number = this.min
      }
      // 如果当前是最小数量，则不操作
      if (this.max <= this.number) {
        this.number = this.max
      }
      // 通知父组件值改变
      this.$emit('onChange', this.number)
    }
  }
}
</script>

<style lang="less" scoped>
.number-container {
  border: 1px solid #ddd;
  user-select: none;
  width: fit-content;
  overflow: hidden;
  .less {
    border-right: 1px solid #ddd;
    color: #999;
    cursor: pointer;
    font-size: 20px;
    float: left;
    width: 36px;
    height: 30px;
    line-height: 30px;
    text-align: center;
  }
  input {
    border: 0px;
    float: left;
    width: 60px;
    height: 30px;
    outline: none;
    text-align: center;
    margin: 0px;
    padding: 0px;
  }
  .more {
    border-left: 1px solid #ddd;
    color: #999;
    cursor: pointer;
    font-size: 20px;
    float: left;
    width: 36px;
    height: 30px;
    line-height: 30px;
    text-align: center;
  }
  .disabled {
    color: #d3d3d3;
    cursor: not-allowed;
  }
}
</style>
